package cn.edu.ahu.aircondition.modbus.service.logic;

import cn.edu.ahu.aircondition.modbus.service.domain.CtrlDomain;
import cn.edu.ahu.aircondition.modbus.service.domain.CtrlRegDomain;
import cn.edu.ahu.aircondition.modbus.service.entity.AirConCtrlEntity;
import cn.edu.ahu.aircondition.modbus.service.entity.AirConSetEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ahu on 2017/6/11.
 */
public class AirConCtrlLogic {
    private SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

    /**
     *
     * @return 设备状态信息
     */
    public List<CtrlDomain> listAirCtrlDomain(){
        Transaction transaction = sessionFactory.getCurrentSession().getTransaction();
        transaction.begin();
        Session session = sessionFactory.getCurrentSession();
        //开始事务
        String queryString = "select setEntity,airConCtrlEntity FROM AirConCtrlEntity " +
                "AS airConCtrlEntity JOIN AirConSetEntity as setEntity ON setEntity.deviceId = airConCtrlEntity.deviceId " +
                "where airConCtrlEntity.status != '执行成功'";
        session.createQuery(queryString);
        List<CtrlDomain> list = objectToAirConControlDomain(session.createQuery(queryString).getResultList());
        transaction.commit();
        session.close();
        return list;
    }
//    /**
//     * 更新数据库中空调状态信息
//     * @param airConCtrlCurEntityList    空调状态信息List
//     */
//    public void updateAirConStatusCur(List<AirConCtrlEntity> airConCtrlCurEntityList){
//        Transaction transaction = sessionFactory.getCurrentSession().getTransaction();
//        transaction.begin();
//        Session session = sessionFactory.getCurrentSession();
//        for (AirConCtrlEntity airConCtrlEntity : airConCtrlCurEntityList){
//            session.update(airConCtrlEntity);
//        }
//        transaction.commit();
//        session.close();
//    }

    private List<CtrlDomain> objectToAirConControlDomain(List list){
        List<CtrlDomain> airConControlDomainList = new ArrayList<CtrlDomain>();
        for (Object object : list){
            airConControlDomainList.add(objectToAirConControlDomain(object));
        }
        return airConControlDomainList;
    }

    private CtrlDomain objectToAirConControlDomain(Object object){
        Object[] obj = (Object[])object;
        return new CtrlDomain((AirConSetEntity)obj[0],(AirConCtrlEntity)obj[1]);
    }
}
